#!/bin/bash
# 获取脚本所在目录
DIRNAME=$(cd "$(dirname "$0")"; pwd)
CONFIG_FILE="${DIRNAME}/apksigner.json"

# 检查依赖工具
check_dependencies() {
  local missing=()
  [ ! -f "$CONFIG_FILE" ] && missing+=("apksigner.json")
  ! command -v jq &> /dev/null && missing+=("jq")
  ! command -v java &> /dev/null && missing+=("Java")
  
  if [ ${#missing[@]} -gt 0 ]; then
    echo "缺失依赖: ${missing[*]}"
    echo "请先安装jq工具: brew install jq (macOS) 或 apt-get install jq (Linux)"
    exit 1
  fi
}

# 读取JSON配置
read_config() {
  BUILD_TOOLS=$(jq -r '.build_tools' "$CONFIG_FILE")
  TARGET_APK=$(jq -r '.target_unsigned_apk' "$CONFIG_FILE")
  CHANNEL=$(jq -r '.channel' "$CONFIG_FILE")
  KEYSTORE_PATH=$(jq -r '.keystore' "$CONFIG_FILE")
  KEY_ALIAS=$(jq -r '.keystore_alias' "$CONFIG_FILE")
  KEYSTORE_PASS=$(jq -r '.keystore_password' "$CONFIG_FILE")
  
  # 处理Windows路径转换（当在Git Bash运行时）
  if [[ "$OSTYPE" == "msys" ]]; then
    BUILD_TOOLS=$(cygpath -u "$BUILD_TOOLS")
    TARGET_APK=$(cygpath -u "$TARGET_APK")
    KEYSTORE_PATH=$(cygpath -u "$KEYSTORE_PATH")
  fi
}

# 主流程
main() {
  check_dependencies
  read_config
  
  # 提取APK名称
  TARGET_APK_NAME=$(basename "$TARGET_APK" .apk)
  OUT_DIR="${DIRNAME}/output"
  mkdir -p "$OUT_DIR"

  echo "=============== CONFIGURATION ================"
  echo "Build Tools: $BUILD_TOOLS"
  echo "Target APK: $TARGET_APK"
  echo "Channel: $CHANNEL"
  echo "Output Dir: $OUT_DIR"
  echo "=============================================="

  # zipalign处理
  echo "=============== zipalign ====================="
  "${BUILD_TOOLS}/zipalign" -v -p 4 "$TARGET_APK" "${TARGET_APK_NAME}-aligned.apk"

# apksigner签名（兼容Windows/macOS/Linux）
echo "=============== apksigner ===================="
APKSIGNER_CMD="apksigner"
if [[ "$OSTYPE" == "msys" ]]; then
  APKSIGNER_CMD="apksigner.bat"
fi

"${BUILD_TOOLS}/${APKSIGNER_CMD}" sign \
  --v1-signing-enabled true \
  --v2-signing-enabled true \
  --ks "$KEYSTORE_PATH" \
  --ks-key-alias "$KEY_ALIAS" \
  --ks-pass "pass:$KEYSTORE_PASS" \
  --key-pass "pass:$KEYSTORE_PASS" \
  --out "${TARGET_APK_NAME}-signed.apk" \
  "${TARGET_APK_NAME}-aligned.apk"
  sleep 3

# VasDolly渠道写入
echo "=============== VasDolly ====================="
# 标准化输出路径（移除末尾可能的/符号）
OUT_DIR="${OUT_DIR%/}"
# 使用双引号包裹路径，避免空格或特殊字符问题
java -jar "${DIRNAME}/VasDolly.jar" put -c "$CHANNEL" \
  "${TARGET_APK_NAME}-signed.apk" "${OUT_DIR}"


  # 清理临时文件
  echo "=============== Cleanup ====================="
  rm -f "${TARGET_APK_NAME}-aligned.apk" "${TARGET_APK_NAME}-signed.apk" *.idsig

  echo "=============== COMPLETE ===================="
  echo "Signed and channeled APK saved to: ${OUT_DIR}/"
}

main "$@"
